/* eslint-disable no-param-reassign */
import React, { useState, useEffect } from 'react';
import { Form, Row, Col, Card, Button, Select, Input, notification } from 'antd';
import { FormComponentProps } from 'antd/es/form';
import { ALL, PAGE } from '@/utils/constant';
import { classList, getTeacher, Editstudents } from '@/services/api';

interface UserFormProps extends FormComponentProps {
  classData: object[];
  history: object;
  studentsData: {};
}

const { Item } = Form;
const MyForm = Form.create<UserFormProps>()(
  ({
    form: { getFieldDecorator, validateFields, resetFields },
    studentsData,
    classData,
    history,
  }: any) => {
    const [teracherIdData, setTeracherIdData] = useState([]);
    const initGrades = JSON.parse(JSON.stringify(classData));
    const extra = studentsData?.extra;
    const formItemLayout = {
      labelCol: {
        xs: { span: 4, offset: 4 },
      },
      wrapperCol: {
        sm: { span: 8 },
      },
    };

    // 请求教师数据
    useEffect(() => {
      getTeacher({ page: PAGE, size: ALL }).then((resp: any) => {
        if (resp.status === 'success') {
          setTeracherIdData(resp.data.data);
        }
      });
    }, []);

    return (
      <Form layout="horizontal" {...formItemLayout}>
        <Item label="姓名">
          {getFieldDecorator('name', {
            initialValue: studentsData.name,
            rules: [
              {
                required: true,
                message: '必填',
              },
            ],
          })(<Input placeholder="请输入" />)}
        </Item>
        <Item label="班级">
          {getFieldDecorator('clase_id', {
            initialValue: studentsData.clase_id,
            rules: [
              {
                required: true,
                message: '必填',
              },
            ],
          })(
            <Select
              placeholder="请选择"
              allowClear
              showSearch
              filterOption={(input: any, option: any) =>
                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
              }
            >
              {initGrades.map((item: any) => (
                <Select.Option value={item.id} key={item.id}>
                  {item.name}
                </Select.Option>
              ))}
            </Select>,
          )}
        </Item>
        <Item label="选择班主任">
          {getFieldDecorator('teacher_id', {
            initialValue: studentsData.teacher && studentsData.teacher.id,
            rules: [
              {
                required: true,
                message: '必填',
              },
            ],
          })(
            <Select
              placeholder="请选择"
              allowClear
              showSearch
              defaultActiveFirstOption={false}
              filterOption
              optionFilterProp="children"
              // onSearch={value => {
              //   if (value) {
              //     const searchValue = value.trim();
              //     getTeacher({ page: PAGE, size: 10, keyword: searchValue }).then((resp: any) => {
              //       if (resp.status === 'success') {
              //         setTeracherIdData(resp.data.data);
              //       }
              //     });
              //   }
              // }}
            >
              {/* {studentsData.teacher && (
                <Select.Option value={studentsData.teacher.id} key={studentsData.teacher.id}>
                  {studentsData.teacher.name}
                </Select.Option>
              )} */}
              {teracherIdData.map((item: any) => (
                <Select.Option value={item.id} key={item.id}>
                  {item.name}
                </Select.Option>
              ))}
            </Select>,
          )}
        </Item>
        <Item label="认领状态">
          {getFieldDecorator('status', {
            initialValue: `${studentsData.status}`,
            rules: [
              {
                required: true,
                message: '必填',
              },
            ],
          })(
            <Select>
              <Select.Option value="0">未认领</Select.Option>
              <Select.Option value="1">已认领</Select.Option>
              <Select.Option value="2">已拒绝</Select.Option>
            </Select>,
          )}
        </Item>
        <Item label="是否交学费">
          {getFieldDecorator('is_paid', {
            initialValue: `${studentsData.is_paid}`,
            rules: [
              {
                required: true,
                message: '必填',
              },
            ],
          })(
            <Select>
              <Select.Option value="true">已缴费</Select.Option>
              <Select.Option value="false">未交费</Select.Option>
            </Select>,
          )}
        </Item>
        <Item label="学费">
          {getFieldDecorator('money', {
            initialValue: studentsData.money / 100,
            rules: [
              {
                required: true,
                message: '必填',
              },
              {
                validator(rule: any, value: any, callback: any) {
                  const reg = /^\d*\.{0,1}\d{0,2}$/;
                  if (!reg.test(value)) {
                    callback(new Error('金额格式错误'));
                  }
                  callback([]);
                },
                message: '金额格式错误',
              },
            ],
          })(<Input addonAfter="元" />)}
        </Item>
        <Item label="是否安排进班">
          {getFieldDecorator('is_arranged', {
            initialValue: `${studentsData.is_arranged}`,
            rules: [
              {
                required: true,
                message: '必填',
              },
            ],
          })(
            <Select>
              <Select.Option value="true">已安排</Select.Option>
              <Select.Option value="false">未安排</Select.Option>
            </Select>,
          )}
        </Item>

        <Item label="民族">
          {getFieldDecorator('national', {
            initialValue: studentsData.national,
            rules: [
              {
                required: true,
                message: '必填',
              },
            ],
          })(<Input placeholder="请输入" />)}
        </Item>

        <Item label="出生日期">
          {getFieldDecorator('birth_day', {
            initialValue: studentsData.birth_day,
            rules: [
              {
                required: true,
                message: '必填',
              },
            ],
          })(<Input placeholder="请输入" />)}
        </Item>

        <Item label="身份证号码">
          {getFieldDecorator('card_id', {
            initialValue: studentsData.card_id,
            rules: [
              {
                required: true,
                message: '必填',
              },
            ],
          })(<Input placeholder="请输入" />)}
        </Item>

        <Item label="监护人">
          {getFieldDecorator('guardian', {
            initialValue: extra?.guardian,
            rules: [
              {
                required: true,
                message: '必填',
              },
            ],
          })(<Input placeholder="请输入" />)}
        </Item>

        <Item label="户籍所在乡镇">
          {getFieldDecorator('town', {
            initialValue: extra?.town,
            rules: [
              {
                required: true,
                message: '必填',
              },
            ],
          })(<Input placeholder="请输入" />)}
        </Item>

        <Item label="户口性质">
          {getFieldDecorator('register_type', {
            initialValue: extra?.register_type,
            rules: [
              {
                required: true,
                message: '必填',
              },
            ],
          })(<Input placeholder="请输入" />)}
        </Item>

        <Item label="学生来源">
          {getFieldDecorator('come_from', {
            initialValue: extra?.come_from,
            rules: [
              {
                required: true,
                message: '必填',
              },
            ],
          })(<Input placeholder="请输入" />)}
        </Item>

        <Item label="政治面貌">
          {getFieldDecorator('politics_status', {
            initialValue: extra?.politics_status,
            rules: [
              {
                required: false,
                message: '不必填',
              },
            ],
          })(<Input placeholder="请输入" />)}
        </Item>

        <Item label="是否残疾">
          {getFieldDecorator('is_disability', {
            initialValue: `${extra.is_disability}`,
            rules: [
              {
                required: true,
                message: '必填',
              },
            ],
          })(
            <Select>
              <Select.Option value="1">是</Select.Option>
              <Select.Option value="0">否</Select.Option>
            </Select>,
          )}
        </Item>

        <Item label="残疾类型">
          {getFieldDecorator('disability_type', {
            initialValue: extra?.disability_type,
            rules: [
              {
                required: false,
                message: '不是必填',
              },
            ],
          })(<Input placeholder="请输入" />)}
        </Item>

        <Item label="残疾等级">
          {getFieldDecorator('disability_level', {
            initialValue: extra?.disability_level,
            rules: [
              {
                required: false,
                message: '不是必填',
              },
            ],
          })(<Input placeholder="请输入" />)}
        </Item>

        <Item label="就读方式（残疾）">
          {getFieldDecorator('study_way', {
            initialValue: extra?.study_way,
            rules: [
              {
                required: false,
                message: '不是必填',
              },
            ],
          })(<Input placeholder="请输入" />)}
        </Item>

        <Row className="rowMarginTop">
          <Col offset={8}>
            <Button
              type="primary"
              onClick={() => {
                validateFields((err: any, val: any) => {
                  // window.console.log(val, 1);
                  const newVal = JSON.parse(JSON.stringify(val));
                  if (!err) {
                    const residence_images: any = [];
                    const health_images: any = [];
                    if (newVal.is_arranged === 'true') {
                      newVal.is_arranged = true;
                    } else {
                      newVal.is_arranged = false;
                    }
                    if (newVal.is_paid === 'true') {
                      newVal.is_paid = true;
                    } else {
                      newVal.is_paid = false;
                    }
                    newVal.id = studentsData.id;
                    studentsData.residences.forEach((item: any) => {
                      residence_images.push(item.id);
                    });
                    studentsData.healths.forEach((item: any) => {
                      health_images.push(item.id);
                    });
                    newVal.residence_images = residence_images;
                    newVal.health_images = health_images;
                    newVal.money *= 100;
                    delete studentsData.parent;
                    delete studentsData.teacher;
                    delete studentsData.clase;
                    delete studentsData.image;
                    delete studentsData.residences;
                    delete studentsData.healths;

                    // 删除val中获取到的 extra 数据
                    const {
                      guardian,
                      town,
                      register_type,
                      come_from,
                      politics_status,
                      disability_type,
                      disability_level,
                      study_way,
                      is_disability,
                    } = val;

                    const newExtra = {
                      ...studentsData.extra,
                      guardian,
                      town,
                      register_type,
                      come_from,
                      politics_status,
                      disability_type,
                      disability_level,
                      study_way,
                      is_disability,
                    };

                    // console.log(newExtra, 2);

                    delete newVal.guardian;
                    delete newVal.town;
                    delete newVal.register_type;
                    delete newVal.come_from;
                    delete newVal.politics_status;
                    delete newVal.disability_type;
                    delete newVal.disability_level;
                    delete newVal.study_way;
                    delete newVal.is_disability;
                    Editstudents({ ...studentsData, ...newVal, extra: newExtra }).then(
                      (resp: any) => {
                        if (resp.status === 'success') {
                          notification.success({
                            message: '编辑成功',
                          });
                          history.go(-1);
                        }
                      },
                    );
                  }
                });
              }}
            >
              提交
            </Button>
            <Button
              className="secondBtn"
              onClick={() => {
                resetFields();
              }}
            >
              重置
            </Button>
          </Col>
        </Row>
      </Form>
    );
  },
);

function EditStudent({ history }: any) {
  const studentsData = JSON.parse(sessionStorage.getItem('studentsData') || '');
  const [classData, setClassData] = useState([]);

  useEffect(() => {
    classList({ page: PAGE, size: ALL }).then((res: any) => {
      if (res.status === 'success') {
        setClassData(res.data.data);
      }
    });
  }, []);
  return (
    <Card title="编辑学生">
      <MyForm classData={classData} history={history} studentsData={studentsData} />
    </Card>
  );
}

export default EditStudent;
